package com.self.console.service;

import com.self.console.proxy.ProxyHttpClient;
import com.self.console.proxy.RequestResult;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Service
public class CrawlQuotationService {
	protected static final Pattern pattern = Pattern.compile("^(-?[0-9])*[.]?([0-9])+$");
	
	public String crawlQuotation() {
		String goldPrice = "";
		try {
			RequestResult result = ProxyHttpClient.httpRequest("http://service.24k99.com/quote/handler/Datas.ashx?page=24k99-gzhjbybj-gzgjhj&vtype=XHWH", "UTF-8");
			String html = result.getContent();
			String[] hts = html.split(",");
			int i = 0;
			for (; i < hts.length; i++) {
				if ("伦敦黄金".equals(hts[i])) {
					break;
				}
			}
			goldPrice = hts[i+1];
			goldPrice = isFloat(goldPrice);
			DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
			goldPrice = decimalFormat.format((Float.parseFloat(goldPrice) + 0.5));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return goldPrice;
	}
	
	/**
	 * 判断行情是否能转换成Float类型
	 */
	protected final static String isFloat(String f) {
		f = f.trim();
		Matcher matcher = pattern.matcher(f);
		if (!matcher.find()) {
			f = "0";
		}		
		return f;
	}

	public static void main(String[] args) {
		CrawlQuotationService service = new CrawlQuotationService();
		service.crawlQuotation();
	}
}
